package be.sc.classicnetwork.dao.hibernate;

import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.util.StringUtils;

import be.sc.classicnetwork.dao.UserDao;
import be.sc.classicnetwork.model.User;

/**
 * User DAO Implementation.
 * 
 */
public class UserDaoImpl extends HibernateGenericDao<User> implements UserDao {

    /**
     * 
     */
    public UserDaoImpl() {
	super();
    }

    /**
     * @param clazz
     */
    public UserDaoImpl(Class<User> clazz) {
	super(clazz);
    }

    /**
     * @see org.acegisecurity.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     */
    public UserDetails loadByUsername(String username) throws UsernameNotFoundException {
	if (!StringUtils.hasText(username)) {
	    return null;
	}

	DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
	criteria.add(Restrictions.eq("username", username));
	criteria.setFetchMode("roles", FetchMode.JOIN);

	// find the user by name
	return (User) DataAccessUtils.uniqueResult(getHibernateTemplate().findByCriteria(criteria));
    }
}
